$.fn.ready(function() {
	
	(function(){
		
		$("#newtag").click(function(){
			if($("#tags").val()!="")
			{
						$.ajax({
						url:"/addNewTag",
						type:"GET",
						data:{course_id:$("#hideid").val(),tag_name:$("#tags").val()},
						success:function(data){
						    var btntag=$('<a class="btn">');
							btntag.append().html($("#tags").val())
							$("#tagp").append(btntag);
						}
						});
						
			}
		});
		
		$("#comment_sbmt").click(function(){
			if($("#comment").val()!="")
			{
						$.ajax({
						url:"/addComment",
						type:"GET",
						data:{course_id:$("#hideid").val(),comment:$("#comment").val()},
						success:function(data){
							location.reload();
						}
						});
						
			}
		});			

		$("#cmt-disagree").click(function(){
			if($("#comment").val()!="")
			{
						$.ajax({
						url:"/disagreeComment",
						type:"GET",
						data:{comment_id:$("#comment_id").val()},
						success:function(data){
						    var btntag=$('<a class="btn">');
							btntag.append().html("test")
							$("#tagp").append(btntag);
						}
						});
						
			}
		});				
		
		$('.categories-div').empty();
		var categories = {
				"Business":[
				            "Human","Finance"],
				"Computer Science":[
				    "Artificial",
				    "intelligence",
				    "Programming",
				    "System",
				    "Security",
				    "Theory",
				    "Data Science",
				    "Web"],
				"Engineering":["Civil","Electrical","Software"],
				"Humanities":[
				              "History",
				              "Art",
				              "Law",
				              "Music",
				              "Education",
				              "Psychology"],
				"Mathematic":[
				              "Probability","Algebra","Geometry"],
				"Science":["Medicine","Healthcare","Physical","Biology","Food"]
				
		};
		
		for(var cat in categories){
			var container = $('<div class="span6">').append(
			'<div class="tag-header"><a href="#">'+cat+'</a></div>');
			for(var i=0;i<categories[cat].length;i++){
				var tag = $('<a href="#" style="margin:3px">').data("tags",cat+" "+categories[cat][i]).html(categories[cat][i]).click(function(){
					$('#queryInput').val($(this).html());
					$('#queryInput').trigger('change');
					$('#searchpath').html($(this).html());
					$('#querySubmit').trigger('click');
				});
				container.append(tag);
			}
			$('.categories-div').append(container);
			
		}
	})();
	
	$("#btnLogin").click(function(){
		$.ajax({
			url:"/ajaxlogin",
			type:"GET",
			data:{email:$("#inputEmail").val(),password:$("#inputPassword").val()},
			success:function(response){
				if(response.status=="successfull")
				{
					window.location="/";
				}
				else if(response.status=="failed"){
					$("#loginAlert").fadeIn();
				}else
				{
					console.log(response);
				}
			}
		});
	});
	
	var selectedSematicPath = null;
	
	$('#queryInput').autocomplete({
		minLength: 3,
		source: function( request, response ) {
	        $.ajax({
	        	url:"/fetchQueryItems",
				type:"GET",
	          data: {
	            query:$('#queryInput').val()
	          },
	          success: function( result ) {
	        	var data = JSON.parse(result);
	            response( $.map( data.result, function( item ) {
	              if(!selectedSematicPath){
	            	  selectedSematicPath = (item.notable ? item.notable.id + "/"+item.name : item.name)
	              }
	              
	              return {
	            	query:item.name,
	                querylong: item.name + (item.notable ? "("+item.notable.name+")" : ""),
	                value: (item.notable ? item.notable.id + "/"+item.name : item.name)
	              }
	            }
	            
	            ));
	          }
	        });
	      },
		focus: function( event, ui ) {
	        $( "#queryInput" ).val( ui.item.query );
	        return false;
	      },
	      select: function( event, ui ) {
	    	selectedSematicPath = ui.item.value;
	        $( "#queryInput" ).val( ui.item.query );
	        return false;
	      }
	}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
	      return $( "<li>" )
	        .append('<a class="ui-corner-all">'+item.querylong+'</a>')
	        .appendTo( ul );
	};
	
	$('#queryInput').change(function(){
		if($(this).val() == ''){
			$('.searchresults-div').empty();
			$('.categories-div').show();
		}
	});
	
	
	var displaySearchResults = function(query){
		$('#searchpath').html("Search path: "+query);
		$.ajax({
        	url:"/search",
			type:"GET",
	          data: {
	            query:selectedSematicPath
	          },
	          success: function( result ) {
	        	$('.categories-div').hide();
	        	var tbl = $('<table class="table">');
 	        	$.each(result,function(idx,item){
	        		var r = $('<tr><td><div><h3><a href="#" class="ahref" tag='+item.id+'>'+item.name+'</a></h3><div><div>'+item.description+'</div></td><<tr>');
	        		r.find('a').first().click(function(){
	        			gotoCoursePage($(this).attr('tag'));
	        		});
	        		r.appendTo(tbl);
	        	});
	        	$('.searchresults-div').empty();
	        	$('.searchresults-div').append(tbl);
	        	if(!result.length){
 	        		$('.searchresults-div').empty();
 	        		$('#searchpath').empty();
 	        		$('.searchresults-div').append($("<h3>").html("Waiting to be discovered. Are you volunteer ?"))
 	        	}
	          }
	    });
	}
	
    
	$('#querySubmit').click(function(){
		if(!selectedSematicPath){
			$.ajax({
	        	url:"/fetchQueryItems",
				type:"GET",
		          data: {
		            query:$('#queryInput').val()
		          },
		          success: function( result ) {
		        	var data = JSON.parse(result);
		        	var defaultVal = $('#queryInput').val();
		        	selectedSematicPath = defaultVal;
		        	if(data.length){
		        		selectedSematicPath = (
		        				data[0].notable 
		        				? data[0].notable.id + "/"+data[0].name 
		        				: defaultVal
		        		);
		        	}
		        	displaySearchResults(selectedSematicPath);
	        	
            }});
        }else{
        	displaySearchResults(selectedSematicPath);
        }
		selectedSematicPath = null;
		return false;
		});
	
	
});

$( "#startDate" ).datepicker();
$( "#endDate" ).datepicker();

function agree(ci)
{
	//alert(ci);
	$.ajax({
	url:"/agreeComment",
	type:"GET",
	data:{comment_id:ci},
	success:function(data){
		alert('Thanks for your vote.');
		location.reload();
	}
	});
	//alert('test:end_line');
}

function disagree(ci)
{
	//alert('test:start_line');
	$.ajax({
	url:"/disagreeComment",
	type:"GET",
	data:{comment_id:ci},
	success:function(data){
		alert('Thanks for your vote.');
		location.reload();
	}
	});
	//alert('test:end_line');
}



var gotoCoursePage=function(id){
	document.location = document.location.origin + "/coursedetail/"+id;
}

